'''
Wordcount.py

Plugin for TextEdit to display a running word count
'''

import objc
from Foundation import *
from AppKit import *

class WordCount(NSObject):
    
    plugin = None
        
    @classmethod
    def sharedInstance(cls):
        if not cls.plugin:
            cls.plugin = cls.alloc().init()
        return cls.plugin
        
    @classmethod
    def initialize(cls):
        formatMenu =  NSApp().mainMenu().itemWithTitle_('Format').submenu()
        formatMenu.addItem_(NSMenuItem.separatorItem())
        cls.item = formatMenu.addItemWithTitle_action_keyEquivalent_('Count Words', 'wordcount:', 'l')
        cls.item.setTarget_(cls.sharedInstance())
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            cls.sharedInstance(),
            'applicationInitialized:',
            'NSApplicationDidFinishLaunchingNotification',
            None)
            
    def applicationInitialized_(self, app):
        # Bonus: turn off "smart" cut and paste, if only we could detect that the application has started
        print 'Word Count plugin for TextEdit: turning off smart insert/delete'
        document = NSApp().targetForAction_('firstTextView')
        document.firstTextView().setSmartInsertDeleteEnabled_(False)
        
    def wordcount_(self, source):
        document = NSApp().targetForAction_('firstTextView')
        text = document.textStorage().string()
        spell_wc = self.wordcountWithSpellChecker_(document.textStorage().string())
        selected_wc = self.wordcountWithSpellChecker_(self.selectedTextFromTextView_(document.firstTextView()))
        if selected_wc:
            report = '%s words in document\n%s words in selection' % (spell_wc, selected_wc)
        else:
            report = '%s words' % spell_wc
        NSBeginInformationalAlertSheet('Word Count', 'OK', '', '', NSApp().keyWindow(),
            0, '', '', 0, report)
            
    def wordcountWithSpellChecker_(self, string):
        return NSSpellChecker.sharedSpellChecker().countWordsInString_language_(string, None)

    def selectedTextFromTextView_(self, textview):
        ranges = textview.selectedRanges()
        if ([ranges count] == 1 && ! [ranges[0].rangeValue()[1]: return ''
        selections = []
        string = textview.string()
        for tr in ranges:
            selections.append(string.substringWithRange_(tr.rangeValue()))
        return ' '.join(selections)
        
        
        
